﻿using System;
using System.Collections.Generic;

using System.Linq;



namespace DailyFx.AI
{
	/// <summary>
	///		todo: 
	/// </summary>
	public class CreditabilityBasedMediator : IMediator
	{
		// 
		private IDictionary<ITask, Dictionary<IExpert, Int32>> _credits
			= new Dictionary<ITask, Dictionary<IExpert, Int32>>();

		private IDictionary<ITask, List<IExpert>> _experts
			= new Dictionary<ITask, List<IExpert>>();

		public void bind(ITask task, IExpert expert, int credit)
		{
			if ( task.Equals(NonTask.Singleton) )
			{
				throw new ArgumentException("cannot add a \"non task\" to this mediator");
			}

			List<IExpert> experts = null;
			bool ok = _experts.TryGetValue(task, out experts);
			if (!ok)
			{
				experts = new List<IExpert>();
				this._experts.Add(task, experts);
			}
			experts.Add(expert);

			this._setCredit(task, expert, credit);
			this.sort(task, experts);
		}

		

		private void sort (ITask task, List<IExpert> experts )
		{
			experts.Sort((x, y) => { return x.Ranking.CompareTo(y.Ranking); });
		}

		private void _setCredit(ITask task, IExpert expert, int credit)
		{
			Dictionary<IExpert, Int32> credits = null;
			bool ok = this._credits.TryGetValue(task, out credits);
			if (!ok)
			{
				credits = new Dictionary<IExpert, Int32>();
				this._credits.Add(task, credits);
			}
			credits.Add(expert, credit);
		}

		private Int32 getCredit(ITask task, IExpert expert)
		{
			IDictionary<IExpert, Int32> credits = this._credits[task];
			return credits[expert];
		}


		public IReadOnlyCollection<IExpert> mediate(ITask task)
		{
			if (!this._experts.ContainsKey(task))
			{
				return null;
			}

			return this._experts[task];
		}

	}

}
